//
//  CPJUserAccount.swift
//  Sina
//
//  Created by YYY on 2017/8/8.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

private let fileName = "userAccount.json"
private let savePath = (kDocumentPath as NSString).appendingPathComponent(fileName)

class CPJUserAccount: NSObject {

    //用户授权的唯一票据 访问令牌
    var access_token: String? //= "2.00gk1fkDjuT3IC2cacdea2136dJVEC"
    
    //access_token的生命周期，单位是秒数
    var expires_in: TimeInterval = 0
    {
        didSet{
            expireDate = Date(timeIntervalSinceNow: expires_in)
            //expireDate = Data(timeIntervalSinceNow: expires_in)
        }
    }
    //过期时间
    var expireDate: Date?
    
    //授权用户的UID
    var uid: String?
    
    //用户昵称
    var screen_name: String?
    
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    override var description: String
    {
        return yy_modelDescription()
    }
    
    //构造函数
    override init() {
        super.init()
        
        guard let data = NSData(contentsOfFile: savePath),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]  else
        {
            return
        }
        //yy_modelSet(字典)
        yy_modelSet(with: dict ?? [:])
        
        //expireDate = Date(timeIntervalSinceNow: -24*3600)
        if expireDate?.compare(Date()) != .orderedDescending
        {
            print("token过期")
            access_token = nil
            uid = nil
            //移除本地文件
            try? FileManager.default.removeItem(atPath: savePath)
            
            NotificationCenter.default.post(name: Notification.Name(rawValue: UserShouldLoginNotification), object: "token过期")
        }
        else
        {
            print("token正常")
        }
        
    }
    func saveAccount()
    {
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        //删除expires_in的值
        dict.removeValue(forKey: "expires_in")
    
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return
        }
        //let fileName = "userAccount.json"
        //let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        //let savePath = (kDocumentPath as NSString).appendingPathComponent(fileName)
        (data as NSData).write(toFile: savePath, atomically: true)
        
    }
}
